/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pb138.odsKartW.web;

import cz.muni.fi.pb138.odsKartW.MediaManager;
import cz.muni.fi.pb138.odsKartW.MediaManagerImpl;
import cz.muni.fi.pb138.odsKartW.MediaSource;
import cz.muni.fi.pb138.odsKartW.Medium;
import cz.muni.fi.pb138.odsKartW.ODSKartWException;
import cz.muni.fi.pb138.odsKartW.Title;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Administrator
 */
public class EditMedium extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet EditMedium</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet EditMedium at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            request.setCharacterEncoding("UTF-8");
        String whatDo = request.getParameter("submit");
        Integer ID = Integer.parseInt(request.getParameter("Id"));
        MediaManager mediaManager = null;
        Medium medium = null;
        String sheetLabel = request.getParameter("categoryTitle");
        request.setAttribute("categoryTitle", sheetLabel);
        
        try {
            MediaSource source = new MediaSource();
            mediaManager = new MediaManagerImpl(new File(request.getSession().getServletContext().getRealPath(source.getSource())));
        } catch (IOException ex) {
            request.setAttribute("error", "Error: "+ex.getMessage());
        } 
        List<String> headerNames= new ArrayList<String>();
        try {
             headerNames = mediaManager.getHeader(sheetLabel);
        } catch (Exception ex) {
            Logger.getLogger(MediaManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", "Error: "+ex.getMessage());
        }
        
        try {
            medium = mediaManager.getMediumAccordingIdAndSheetLabel(ID, sheetLabel);
        } catch (ODSKartWException ex) {
            Logger.getLogger(MediaManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
            request.setAttribute("error", "Error: "+ex.getMessage());
        }
        
        List<TextFiller> textFiller = new ArrayList<TextFiller>();
        for (int i=0;i<medium.getTitles().size();i++){
            TextFiller one = new TextFiller();
            one.setHeader(headerNames.get(i+1));
            one.setValue(medium.getTitles().get(i).getName());
            textFiller.add(one);
        }
        
        request.setAttribute("textFiller", textFiller);
        request.setAttribute("medium", medium);
        
        if (whatDo!=null){
            if (whatDo.equals("Vymaž z databázy")){
                try {
                    mediaManager.deleteMediumAccordingIdAndSheetLabel(ID, sheetLabel);
                } catch (ODSKartWException ex) {
                    request.setAttribute("error", "Error: "+ex.getMessage());
                }
            }
            if (whatDo.equals("Uprav")){
                try {
                    medium = new Medium(sheetLabel);
                    medium.setID(ID);
                    for(String s : headerNames) {
                        if(!s.equals("Id")) {
                            medium.getTitles().add(new Title(request.getParameter(s)));
                        }
                    }
                    mediaManager.updateMedium(medium);
                    
                } catch (ODSKartWException ex) {
                    request.setAttribute("error", "Error: "+ex.getMessage());
                    request.getRequestDispatcher("edit.jsp").forward(request, response);
                }
            }
            if (whatDo.equals("Zruš")){
            }
            try {
                ShowMedia showMedia = new ShowMedia();
                showMedia.setDataShow(request);  
                request.setAttribute("show", true);
                request.getRequestDispatcher("index.jsp").forward(request, response);
                return;
            } catch (ServletException ex){
                Logger.getLogger(MediaManagerImpl.class.getName()).log(Level.SEVERE, null, ex);
                request.setAttribute("error", "Error: "+ex.getMessage());
            }
        }
        
        request.getRequestDispatcher("edit.jsp").forward(request, response);
    }
    
    public class TextFiller{
        private String header;
        private String value;
        public void setHeader(String header){
            this.header = header;
            
        }
        public void setValue(String value){
            this.value = value;
        }
        public String getHeader(){
            return header;
        }
        public String getValue(){
            return value;
        }
    } 
    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
